package com.hzc.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hzc.common.to.mq.SecKillOrderTo;
import com.hzc.common.utils.R;
import com.hzc.common.vo.MemberRsepVo;
import com.hzc.gulimall.seckill.feign.CouponFeignService;
import com.hzc.gulimall.seckill.feign.ProductFeignService;
import com.hzc.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.hzc.gulimall.seckill.service.SeckillService;
import com.hzc.gulimall.seckill.to.SeckillSkuRedisTo;
import com.hzc.gulimall.seckill.vo.SeckillSessionVo;
import com.hzc.gulimall.seckill.vo.SeckillSkuRelationVo;
import com.hzc.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stocks:";

    @Override
    public void uploadSeckillSkuLatest3Day() {
        //1、扫描最近三天需要参与秒杀的活动
        R session = couponFeignService.getLatest3DaySession();
        if (session.getCode() == 0) {
            //上架商品
            List<SeckillSessionVo> sessionData = (List<SeckillSessionVo>) session.getData(new TypeReference<List<SeckillSessionVo>>() {
            });
            //缓存到redis
            //1、缓存活动信息
            saveSessionInfos(sessionData);
            //2、缓存活动的关联商品信息
            saveSessionSkuInfos(sessionData);
        }
    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e) {
        log.error("getCurrentSeckillSkusResource被限流了...");
        return null;
    }

    @SentinelResource(value = "getCurrentSeckillSkusResource", blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1、确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        try (Entry entry = SphU.entry("seckillSkus")) {
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if (time >= start && time <= end) {
                    //2、获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流,{}", e.getMessage());
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //找到所有参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                //6_4
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //如果没到秒杀时间，随机码不应该返回
                    long current = new Date().getTime();
                    if (current >= redisTo.getStartTime() && current <= redisTo.getEndTime()) {

                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRsepVo respVo = LoginUserInterceptor.loginUser.get();
        //1、获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
        //校验时间合法性
        Long startTime = redisTo.getStartTime();
        Long endTime = redisTo.getEndTime();
        long curTime = new Date().getTime();
        long ttl = endTime - startTime;
        if (!(curTime >= startTime && curTime <= endTime)) {
            return null;
        }
        //校验随机码
        String randomCode = redisTo.getRandomCode();
        if (!randomCode.equals(key)) {
            return null;
        }
        //验证购物数量
        if (num > redisTo.getSeckillLimit()) {
            return null;
        }
        //验证这个人是否购买过。幂等性：只要秒杀成功，就去占位
        //userId_sessionId_skuId   setnx原子性的
        String redisKey = respVo.getId() + "_" + killId;
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
        if (!aBoolean) {
            return null;
        }
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + key);
        boolean b = semaphore.tryAcquire(num);
        if (!b) {
            return null;
        }
        //秒杀成功、快速下单
        String orderSn = IdWorker.getTimeId();
        SecKillOrderTo orderTo = new SecKillOrderTo();
        orderTo.setOrderSn(orderSn);
        orderTo.setMemberId(respVo.getId());
        orderTo.setNum(num);
        orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
        orderTo.setSkuId(redisTo.getSkuId());
        orderTo.setSeckillPrice(redisTo.getSeckillPrice());
        rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
        return orderSn;
    }

    //缓存活动信息
    private void saveSessionInfos(List<SeckillSessionVo> sessions) {
        if (sessions == null) {
            return;
        }
        sessions.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionVo> sessions) {
        sessions.stream().forEach(session -> {
            //准备哈希操作
            BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuRelationVo -> {
                String token = UUID.randomUUID().toString().replace("-", "");
                //保证幂等性
                if (!ops.hasKey(seckillSkuRelationVo.getPromotionSessionId().toString() + "_" + seckillSkuRelationVo.getSkuId().toString())) {
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1、sku基本信息
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuRelationVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVo info = (SkuInfoVo) skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(info);
                    }
                    //2、sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuRelationVo, redisTo);
                    //3、时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    //4、随机码
                    redisTo.setRandomCode(token);
                    String s = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuRelationVo.getPromotionSessionId().toString() + "_" + seckillSkuRelationVo.getSkuId().toString(), s);
                    //引入分布式信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuRelationVo.getSeckillCount());
                }
            });
        });
    }
}
